package cn.com.easy.permission.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.easy.permission.dao.ResourceDao;
import cn.com.easy.permission.dao.UserDao;
import cn.com.easy.permission.model.ResourceModel;
import cn.com.easy.permission.model.UserModel;
import cn.com.easy.permission.service.system.userindex.UserIndexService;
import cn.com.easy.utils.RequestUtils;

/**
 * 首页控制器
 * 
 * @author nibili 2014-12-21
 * 
 */
@Controller
@RequestMapping("/manage/")
public class SystemUserIndexController extends BaseController {

	/** 首页，用户菜单tag, */
	private static final String USER_INDEX_MENU_TAG = "UserMenu";

	/**
	 * 用户信息dao
	 */
	@Autowired
	private UserDao userDao;

	/** 权限资源dao */
	@Autowired
	private ResourceDao resourceDao;

	/** 登录服务类 */
	@Autowired
	private UserIndexService loginService;

	/**
	 * 登录到首页
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(HttpServletRequest request, HttpServletResponse response) {
		// 设置用户权限
		this.setIndexMenuAndPermission(request);
		return "/system/system_user_index/system_user_index";
	}

	/**
	 * 设置用户首页菜单及权限
	 * 
	 * @auth nibili 2015年12月11日 下午11:45:09
	 */
	private void setIndexMenuAndPermission(HttpServletRequest request) {
		// 当前用户
		UserModel userModel = this.getCurrentUser(request);
		if (userModel.getLoginname().equals("admin") == true || (userModel.getIsAdmin() != null && userModel.getIsAdmin() == true)) {
			// 所有资源
			List<ResourceModel> resourceModels = resourceDao.findAll(new Sort(new Order(Direction.ASC, "showIndex")));
			// 菜单
			request.getSession().setAttribute(USER_INDEX_MENU_TAG, loginService.getResourceDto(resourceModels));
		} else {
			// 还没有设置权限，从数据库中读取权限
			List<ResourceModel> resourceModels = resourceDao.findByUserId(userModel.getId());
			// 菜单
			request.getSession().setAttribute(USER_INDEX_MENU_TAG, loginService.getResourceDto(resourceModels));
			// 权限
			RequestUtils.setUserPermission(request, loginService.getPermissions(resourceModels));
		}
	}
}
